//
//  LWOAouthViewController.swift
//  Microblog
//
//  Created by Roman on 17/1/7.
//  Copyright © 2017年 Roman. All rights reserved.
//

import UIKit
import SVProgressHUD

class LWOAouthViewController: UIViewController{

    let webView = UIWebView()
    //创建UIwebView页面
    override func loadView() {
    //1.自定义视图
        view = webView
        //2.代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close))
        
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "走后门", target: self, action: #selector(fillAccount))
    
        self.view.backgroundColor = UIColor.white
        
        //请求授权页面
        loadOaouthPage()
    }
    func loadOaouthPage()  {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=354511372&redirect_uri=https://git.oschina.net/Romam"
        
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        webView.loadRequest(req)
        
        
    }
    
    //左侧Button 的点击
   @objc private func close()  {
        dismiss(animated: true, completion: nil)
        
    }
    //右侧按钮的点击,实现跳转到webView 页面
    @objc private func fillAccount()  {
        let jsString = "document.getElementById('userId').value = '15200531442',document.getElementById('passwd').value = '123456789'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    
    }
    
 

}

extension LWOAouthViewController: UIWebViewDelegate{
    
    //MARK :实现协议方法
    func webViewDidStartLoad(_ webView: UIWebView) {
        //显示指示器
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //dismiss指示器
        SVProgressHUD.dismiss()
    }
    
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //https://git.oschina.net/Romam?code=9990ee2b279ef98e06eb73f343cf4e16
        let urlString = request.url?.absoluteString ?? ""
        //判断urlString 中是否包含了特殊的标记如果包含就可以截取code
        let flag = "code="
        if urlString.contains(flag) {
            //可以截取code
            let query = request.url?.query ?? ""
            let code = (query as NSString).substring(from: flag.characters.count)
            print(code)
            //通过code 获取令牌
            //使用账户的视图模型的单利对象来调用获取token的方法
            LWUserAccountViewModel.shard.loadAccessToken(code: code, finshed: { (success) in
                if !success {
                    //没有成功
                    SVProgressHUD.showError(withStatus: "登录失败")
                }
                
                print("用户登录成功")
                //跳转到欢迎页面 欢迎用户,在用户欢迎页面会出现用户头像无法显示
                //需要确保视图模型的单例对象的account 在未登录状态到登录状态的情况下能够有值
                //使用根视图控制器来切换.
               // UIApplication.shared.keyWindow?.rootViewController = LWWelcomViewController()
                //接受通知
                NotificationCenter.default.post(name: NSNotification.Name.AppChangRootVC, object: "LWWelcomViewController")
                
            })
            return false
            
        }
        print(urlString)
        
        return true
    }
    /*
    //2.通过Code 请求令牌
    private func loadAccessToken(code: String)  {
        //请求接口 获取令牌
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let dict = ["client_id":client_id,
                    "client_secret":client_secret,
                    "grant_type":"authorization_code",
                    "code":code,
                    "redirect_uri":redirect_uri]
        
        
        HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: dict) { (responseObject, error) in
            if error != nil{
                SVProgressHUD.showError(withStatus: "没有网络,登录失败!")
            }
            
            //请求成功 AFN内部会将二进制的数据反序列化成为json数据
            //print(responseObject!)
            //3.通过令牌请求用户信息
            self.loadUserInfo(dict: responseObject as! [String : Any])
        }
    }
    
    //3.通过令牌请求用户信息
    private func loadUserInfo(dict : [String :Any]){
        //参数: access_token  uid  加!进行强制解包,使下面parameters 打印出来不会出现 Optional
        let access_token = dict["access_token"]!
        let uid = dict["uid"]!
        
        let parameters = ["access_token":access_token,
                          "uid":uid]
        print(parameters)
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil{
                SVProgressHUD.showError(withStatus: "没有网络,登录失败!")
                return
            }
            //请求成功
            //3.1 将授权信息和用户信息进行合并
            var userInfoDict = responseObject as! [String : Any]
            for (key,value) in dict{
                userInfoDict[key] = value
            }
            
            //3.2 将所有的信息转换为模型数据
            let userAccount = LWUserAccountModel(dict: userInfoDict)
            //4. 将模型数据通过归档的方式存储到沙盒中 将用户信息在本地保存(方便以后使用)/服务器保存(没有服务器不做)
            self.saveUserAccount(account: userAccount)
        }
    }
    
    //4.将用户信息在本地保存方便以后使用
    private func saveUserAccount(account: LWUserAccountModel){
        //归档 到沙盒中Document/Library
        //拼接文件路径的方法 在String中并没有 需要转换为NSString AS前面的对象不能为可选对象
        let path = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")
        
        NSKeyedArchiver.archiveRootObject(account, toFile: path)
        
        print(path)
        
    }
 */
    
    

}


